package auth

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"time"
)

var jwtkey = []byte("zhuangxingeng&chenjiarun&chenjunwei*chehuicheng")
var str string

type Claims struct {
	UserId string
	jwt.StandardClaims
}

func GetToken(ctx *gin.Context, userId string) string {
	expireTime := time.Now().Add(10 * time.Minute)
	claims := &Claims{
		UserId: userId,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(), //过期时间
			IssuedAt:  time.Now().Unix(),
			Issuer:    "zhuangxingeng", // 签名颁发者
			Subject:   "user token",    //签名主题
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtkey)
	if err != nil {
		fmt.Println(err)
	}
	str = tokenString
	return str
}

func GetClaims(ctx *gin.Context) *Claims {
	tokenString := ctx.GetHeader("Authorization")
	if tokenString == "" {
		return &Claims{UserId: ""}
	}

	token, claims, err := ParseToken(tokenString)
	if err != nil || !token.Valid {
		return &Claims{UserId: ""}
	}
	return claims
}

func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	Claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, Claims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtkey, nil
	})
	return token, Claims, err
}
